import os
try:
    from twisted.internet import epollreactor as bestreactor
    print "using epoll..."
except:
    try:
        from twisted.internet import pollreactor as bestreactor
        print "using poll..."
    except:
        from twisted.internet import selectreactor as bestreactor
        print "using select..."
bestreactor.install()

from twisted.internet import reactor, protocol, defer
from twisted.internet import ssl
import sys
from twisted.protocols.basic import LineReceiver

class WebAdminProtocol(LineReceiver):
    def lineReceived(self, data):
        def finish_call ():
            s = """HTTP/1.1 200 OK
Date: Tue, 16 Feb 2010 17:00:06 GMT
Content-Type: text/plain
Content-Length: 2
Server: Twisted/9.0.0

{}"""
            msg = s
            self.transport.write(msg)
            self.transport.loseConnection()

        if data.startswith("GET /"):
            reactor.callLater(2, finish_call)

class WebAdminFactory(protocol.ServerFactory):
    protocol  = WebAdminProtocol
    def __init__ (self, moClient):
        self.moClient = moClient

def main():
    reactor.listenTCP(8081, WebAdminFactory(None))
    reactor.run()


if __name__ == "__main__":
    # do the UNIX double-fork magic, see Stevens' "Advanced
    # Programming in the UNIX Environment" for details (ISBN 0201563177)
    if os.name == "posix":
        f = file("longtask.pid", "w+")
        try:
            pid = os.fork()
            if pid > 0:
                # exit first parent
                sys.exit(0)
        except OSError, e:
            print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
            sys.exit(1)

        # decouple from parent environment
        #os.chdir("/")
        os.setsid()
        os.umask(0)

        # do second fork
        try:
            pid = os.fork()
            if pid > 0:
                # exit from second parent, print eventual PID before
                print "Daemon PID %d" % pid
                f.write(str(pid))
                f.close()
                sys.exit(0)
        except OSError, e:
            print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
            sys.exit(1)

    main()
